
// Utilities for forms
var FormUtils = function() {
	
	// Checks if a value is null or empty
	var isEmpty = function(val) {
		return val == null || val.length == 0;
	};

	// Checks if value matches an email format
	var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	var isEmail = function(val) {
		return emailRegex.test(val);
	};

	// Checks if value matches a username format
	var usernameRegex = /^[a-zA-Z0-9]+$/;
	var isUsername = function(val) {
		return usernameRegex.test(val);
	};
	
	// Checks if value matches a password format
	var isPassword = function(val) {
		return val.length >= 6 && val.search(/[a-zA-Z]/) != -1 && val.search(/\d/) != -1;
	};

	// Removes an inputs message
	var removeMessage = function(el) {
		$(el).parent().removeClass('error').removeClass('valid');
	};

	// Shows an input error message
	var showError = function(el, message, selectAll) {
		$(el).parent().removeClass('valid').addClass('error').find('.inputicon').text(message);
		if(selectAll) {
			$(el).select();
		}
	};

	// Shows a valid input
	var showValid = function(el) {
		$(el).parent().removeClass('error').addClass('valid').find('.inputicon').empty();
	};

	return {
		
		// Validates an email address
		validateEmail: function(el, emptyIsFail, selectOnFail) {
			var value = $(el).val();
			if(!emptyIsFail && isEmpty(value)) {
				removeMessage(el);
				return false;
			} else if(isEmail(value) == false) {
				showError(el, 'Please enter a valid email address e.g. someone@mail.com', selectOnFail);
				return false;
			} else {
				showValid(el);
				return true;
			}
		},
		
		// Validates a username
		validateUsername: function(el, emptyIsFail, selectOnFail) {
			var value = $(el).val();
			if(!emptyIsFail && isEmpty(value)) {
				removeMessage(el);
				return false;
			} else if(isUsername(value) == false) {
				showError(el, 'Please enter a valid player name, only letters and numbers', selectOnFail);
				return false;
			} else {
				showValid(el);
				return true;
			}
		},
		
		// Validates a password
		validatePassword: function(el, emptyIsFail, selectOnFail) {
			var value = $(el).val();
			if(!emptyIsFail && isEmpty(value)) {
				removeMessage(el);
				return false;
			} else if(isPassword(value) == false) {
				showError(el, 'Please enter a valid password, at least six characters, must include one letter and one number', selectOnFail);
				return false;
			} else {
				showValid(el);
				return true;
			}
		}
	};
	
}();